package com.jianwei.service.snowflake;

import com.jianwei.configuration.Module;
import com.jianwei.configuration.SnowflakeConfiguration;
import com.jianwei.service.IdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wjwei
 */
@Module("snowflake.enable")
@Service
@Slf4j
public class SnowflakeIdService implements IdService {


    @Override
    public long getNextId() {
        return nextId();
    }

    @Override
    public long getNextId(String businessType) {
        return getNextId();
    }

    @Override
    public Set<Long> batchGetNextId(int batchSize) {
        if ((batchSize % SEQUENCE_MAX) == 0) {
            throw new IllegalArgumentException("batch size " + batchSize + " should be less than the sequence_max queue size");
        }
        Set<Long> nextIds = new HashSet<>(batchSize);
        for (int i = 0; i < batchSize; i++) {
            nextIds.add(nextId());
        }
        return nextIds;
    }

    @Override
    public Set<Long> batchGetNextId(String businessType, int batcSize) {
        return batchGetNextId(batcSize);
    }

    /**
     * 初始偏移时间戳
     */
    private static final long OFFSET = 1546300800L;

    /**
     * 机器id (0~15 保留 16~31作为备份机器)
     */
    private static int WORKER_ID = 1;
    /**
     * 机器id所占位数 (5bit, 支持最大机器数 2^5 = 32)
     */
    private static final long WORKER_ID_BITS = 5L;
    /**
     * 自增序列所占位数 (16bit, 支持最大每秒生成 2^16 = ‭65536‬)
     */
    private static final long SEQUENCE_ID_BITS = 16L;
    /**
     * 机器id偏移位数
     */
    private static final long WORKER_SHIFT_BITS = SEQUENCE_ID_BITS;
    /**
     * 自增序列偏移位数
     */
    private static final long OFFSET_SHIFT_BITS = SEQUENCE_ID_BITS + WORKER_ID_BITS;
    /**
     * 机器标识最大值 (2^5 / 2 - 1 = 15)
     */
    private static final long WORKER_ID_MAX = ((1 << WORKER_ID_BITS) - 1) >> 1;
    /**
     * 备份机器ID开始位置 (2^5 / 2 = 16)
     */
    private static final long BACK_WORKER_ID_BEGIN = (1 << WORKER_ID_BITS) >> 1;
    /**
     * 自增序列最大值 (2^16 - 1 = ‭65535)
     */
    private static final long SEQUENCE_MAX = (1 << SEQUENCE_ID_BITS) - 1;
    /**
     * 发生时间回拨时容忍的最大回拨时间 (秒)
     */
    private static final long BACK_TIME_MAX = 1L;

    /**
     * 上次生成ID的时间戳 (秒)
     */
    private static long lastTimestamp = 0L;
    /**
     * 当前秒内序列 (2^16)
     */
    private static long sequence = 0L;
    /**
     * 备份机器上次生成ID的时间戳 (秒)
     */
    private static long lastTimestampBak = 0L;
    /**
     * 备份机器当前秒内序列 (2^16)
     */
    private static long sequenceBak = 0L;

    @Autowired
    private SnowflakeConfiguration configuration;

    @PostConstruct
    public void init() {
        WORKER_ID = configuration.getWorkers();
        if (WORKER_ID < 0 || WORKER_ID > WORKER_ID_MAX) {
            throw new IllegalArgumentException(String.format("snowflake.workers范围: 0 ~ %d 目前: %d", WORKER_ID_MAX, WORKER_ID));
        }
    }

    /**
     * 获取自增序列
     *
     * @return long
     */
    public static long nextId() {
        return nextId(SystemClock.now() / 1000);
    }

    /**
     * 主机器自增序列
     *
     * @param timestamp 当前Unix时间戳
     * @return long
     */
    private static synchronized long nextId(long timestamp) {
        // 时钟回拨检查
        if (timestamp < lastTimestamp) {
            // 发生时钟回拨
            log.warn("时钟回拨, 启用备份机器ID: now: [{}] last: [{}]", timestamp, lastTimestamp);
            return nextIdBackup(timestamp);
        }

        // 开始下一秒
        if (timestamp != lastTimestamp) {
            lastTimestamp = timestamp;
            sequence = 0L;
        }
        if (0L == (++sequence & SEQUENCE_MAX)) {
            // 秒内序列用尽
            log.warn("秒内[{}]序列用尽, 启用备份机器ID序列", timestamp);
            sequence--;
            return nextIdBackup(timestamp);
        }

        return ((timestamp - OFFSET) << OFFSET_SHIFT_BITS) | (WORKER_ID << WORKER_SHIFT_BITS) | sequence;
    }

    /**
     * 备份机器自增序列
     *
     * @param timestamp timestamp 当前Unix时间戳
     * @return long
     */
    private static long nextIdBackup(long timestamp) {
        if (timestamp < lastTimestampBak) {
            if (lastTimestampBak - SystemClock.now() / 1000 <= BACK_TIME_MAX) {
                timestamp = lastTimestampBak;
            } else {
                throw new RuntimeException(String.format("时钟回拨: now: [%d] last: [%d]", timestamp, lastTimestampBak));
            }
        }

        if (timestamp != lastTimestampBak) {
            lastTimestampBak = timestamp;
            sequenceBak = 0L;
        }

        if (0L == (++sequenceBak & SEQUENCE_MAX)) {
            // 秒内序列用尽
            log.warn("秒内[{}]序列用尽, 备份机器ID借取下一秒序列", timestamp);
            return nextIdBackup(timestamp + 1);
        }

        return ((timestamp - OFFSET) << OFFSET_SHIFT_BITS) | ((WORKER_ID ^ BACK_WORKER_ID_BEGIN) << WORKER_SHIFT_BITS) | sequenceBak;


    }


    public static long getId() {
        return nextId();
    }

    public static String getStringId() {
        return String.valueOf(getId());
    }

    public static class SystemClock {

        private final long period;
        private final AtomicLong now;

        private SystemClock(long period) {
            this.period = period;
            this.now = new AtomicLong(System.currentTimeMillis());
            scheduleClockUpdating();
        }

        /**
         * 尝试下枚举单例法
         */
        private enum SystemClockEnum {
            SYSTEM_CLOCK;
            private final SystemClock systemClock;

            SystemClockEnum() {
                systemClock = new SystemClock(1);
            }

            public SystemClock getInstance() {
                return systemClock;
            }
        }

        /**
         * 获取单例对象
         *
         * @return com.cmallshop.module.core.commons.util.sequence.SystemClock
         */
        private static SystemClock getInstance() {
            return SystemClockEnum.SYSTEM_CLOCK.getInstance();
        }

        /**
         * 获取当前毫秒时间戳
         *
         * @return long
         */
        public static long now() {
            return getInstance().now.get();
        }

        /**
         * 起一个线程定时刷新时间戳
         */
        private void scheduleClockUpdating() {
            ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
                Thread thread = new Thread(runnable, "System Clock");
                thread.setDaemon(true);
                return thread;
            });
            scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
        }

    }

}
